package com.xzy.java.aaa;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Map;

/**
 * 泛型类
 *
 * @author xzy.xiao
 * @date 2023/3/8  14:58
 */
@Slf4j
public class AaaTest {
    private Map<String, Integer> map;

    public static void main(String[] args) throws NoSuchFieldException {
        Field field = AaaTest.class.getDeclaredField("map");
        Type genericType = field.getGenericType();

        /*
         * ParameterizedType：参数化类型，例如List<T>，Set<T>，Map<K,V>
         */
        if (genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;

            /*
             * 获取外部类的Type信息：以 Map.Entry 为例，它的外部类就是 Map
             */
            Type ownerType = parameterizedType.getOwnerType();
            log.info(String.valueOf(ownerType));

            /*
             * 获取原始类型信息：
             *     List<Integer> => List
             *     Set<Integer> => Set
             *     Map<String,Integer> => Map
             */
            Type rawType = parameterizedType.getRawType();
            log.info(String.valueOf(rawType));

            /*
             * 获取类型参数信息：
             *     List<Integer> => [Integer]
             *     Set<Integer> => [Integer]
             *     Map<String,Integer> => [String,Integer]
             */
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            log.info(String.valueOf(Arrays.asList(actualTypeArguments)));
        }
    }
}
